<template>
  <div class="practice">
    <h1 class="page-title">练习学习</h1>
    
    <!-- 练习配置区域 -->
    <el-card v-if="!practicing" class="config-card">
      <template #header>
        <div class="card-header">
          <span>练习配置</span>
        </div>
      </template>
      
      <div class="config-form">
        <!-- 学科选择 -->
        <div class="form-item">
          <label>学科</label>
          <el-select v-model="selectedSubject" placeholder="选择学科" @change="loadKnowledgePoints">
            <el-option
              v-for="subject in subjects"
              :key="subject.id"
              :label="subject.name"
              :value="subject.value">
            </el-option>
          </el-select>
        </div>
        
        <!-- 知识点选择 -->
        <div class="form-item">
          <label>知识点</label>
          <el-input 
            v-model="selectedKnowledgePoint" 
            placeholder="请输入知识点" 
            :disabled="!selectedSubject"
          ></el-input>
        </div>
        
        <!-- 题目数量选择 -->
        <div class="form-item">
          <label>题目数量</label>
          <el-slider v-model="exerciseCount" :min="3" :max="20" :step="1" show-stops show-input></el-slider>
        </div>
        
        <!-- 难度选择 -->
        <div class="form-item">
          <label>难度</label>
          <el-radio-group v-model="difficulty">
            <el-radio :label="'简单'">简单</el-radio>
            <el-radio :label="'中等'">中等</el-radio>
            <el-radio :label="'困难'">困难</el-radio>
          </el-radio-group>
        </div>
        
        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="startPractice" :disabled="!canStartPractice">
            开始练习
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 练习区域 -->
    <div v-else class="practice-area">
      <!-- 练习进度 -->
      <div class="practice-progress">
        <div class="progress-info">
          <span>题目 {{ currentQuestionIndex + 1 }}/{{ exercises.length }}</span>
          <span>用时: {{ formatTime(elapsedTime) }}</span>
        </div>
        <el-progress :percentage="(currentQuestionIndex + 1) / exercises.length * 100" :show-text="false"></el-progress>
      </div>
      
      <!-- 当前习题 -->
      <el-card class="question-card">
        <div class="question-header">
          <div class="question-type">{{ currentExercise.type }}</div>
          <div class="question-info">{{ selectedSubject }} | {{ selectedKnowledgePoint || '综合' }}</div>
        </div>
        
        <div class="question-content" v-html="currentExercise.content"></div>
        
        <!-- 添加答题区域 -->
        <div class="answer-area">
          <!-- 选择题 -->
          <div v-if="currentExercise.type === '选择题'" class="options-container">
            <div class="options-label">请选择答案：</div>
            <div class="options-list">
              <div 
                v-for="option in ['A', 'B', 'C', 'D']" 
                :key="option"
                :class="['option-btn', {'option-selected': userAnswers[currentQuestionIndex] === option}]"
                @click="selectOption(option)"
              >
                {{ option }}
              </div>
            </div>
          </div>
          
          <!-- 填空题 -->
          <div v-else-if="currentExercise.type === '填空题'" class="fill-answer-container">
            <div class="fill-label">你的答案:</div>
            <el-input
              v-model="userAnswers[currentQuestionIndex]"
              type="text"
              placeholder="请输入答案..."
              @keyup.enter="checkAnswer"
            ></el-input>
          </div>
          
          <!-- 简答题 -->
          <div v-else class="essay-answer-container">
            <div class="essay-label">你的答案:</div>
            <el-input
              v-model="userAnswers[currentQuestionIndex]"
              type="textarea"
              :rows="4"
              placeholder="请输入你的答案..."
            ></el-input>
          </div>
          
          <!-- 提交按钮 -->
          <div class="answer-actions">
            <el-button type="primary" @click="checkAnswer" class="submit-btn">提交答案</el-button>
          </div>
          
          <!-- 验证结果 -->
          <div v-if="answerValidated && currentQuestionIndex === validatedQuestionIndex" 
               :class="['validation-result', isCorrect ? 'correct' : 'incorrect']">
            {{ isCorrect ? '✓ 回答正确!' : '✗ 回答错误!' }}
            <div v-if="!isCorrect" class="correct-answer-display">
              正确答案: {{ currentExercise.answer }}
            </div>
            
            <!-- 添加明确的确认按钮 -->
            <div class="confirm-actions">
              <el-button type="success" @click="confirmAnswer" class="confirm-btn">
                {{ currentQuestionIndex < exercises.length - 1 ? '确认并继续' : '确认并完成' }}
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 上一题/下一题按钮 -->
        <div class="question-actions">
          <el-button @click="previousQuestion" :disabled="currentQuestionIndex === 0">上一题</el-button>
          <el-button type="primary" @click="nextQuestion" v-if="!answerValidated && currentQuestionIndex < exercises.length - 1" :disabled="!userAnswers[currentQuestionIndex]">下一题</el-button>
          <el-button type="success" @click="submitPractice" v-if="!answerValidated && currentQuestionIndex === exercises.length - 1" :disabled="!userAnswers[currentQuestionIndex]">完成练习</el-button>
        </div>
      </el-card>
      
      <!-- 题目导航 -->
      <div class="question-nav">
        <div 
          v-for="(_, index) in exercises" 
          :key="index"
          :class="['nav-item', {
            'nav-current': index === currentQuestionIndex,
            'nav-answered': userAnswers[index] && userAnswers[index].length > 0,
            'nav-correct': validatedAnswers[index] && validatedAnswers[index].isCorrect,
            'nav-incorrect': validatedAnswers[index] && !validatedAnswers[index].isCorrect
          }]"
          @click="goToQuestion(index)"
        >
          {{ index + 1 }}
        </div>
      </div>
    </div>
    
    <!-- 练习结果 -->
    <el-dialog v-model="showResult" title="练习结果" width="70%" :close-on-click-modal="false">
      <div class="result-summary">
        <div class="result-item">
          <div class="result-label">正确率</div>
          <div class="result-value">{{ practiceResult.correctRate }}%</div>
        </div>
        <div class="result-item">
          <div class="result-label">用时</div>
          <div class="result-value">{{ formatTime(practiceResult.totalTime) }}</div>
        </div>
        <div class="result-item">
          <div class="result-label">得分</div>
          <div class="result-value">{{ practiceResult.score }}</div>
        </div>
      </div>
      
      <div class="result-analysis" v-if="practiceResult.analysis">
        <h3>分析与建议</h3>
        <div v-html="practiceResult.analysis"></div>
      </div>
      
      <div class="result-questions">
        <h3>题目详情</h3>
        <div v-for="(question, index) in practiceResult.questions" :key="index" class="result-question">
          <div class="question-header">
            <div :class="['question-status', question.isCorrect ? 'status-correct' : 'status-wrong']">
              {{ question.isCorrect ? '正确' : '错误' }}
            </div>
            <div class="question-number">题目 {{ index + 1 }}</div>
          </div>
          
          <div class="question-detail">
            <div class="question-content" v-html="question.content"></div>
            <div class="answer-section">
              <div class="your-answer">
                <div class="answer-label">你的答案:</div>
                <div class="answer-content" v-html="question.userAnswer"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">正确答案:</div>
                <div class="answer-content" v-html="question.correctAnswer"></div>
              </div>
            </div>
            <div class="answer-explanation" v-if="question.explanation">
              <div class="explanation-label">解析:</div>
              <div class="explanation-content" v-html="question.explanation"></div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPractice">重新练习</el-button>
          <el-button type="primary" @click="goToErrorBook">查看错题本</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import { checkAnswerMatch, formatFillinQuestion } from '@/utils/exerciseUtils';

const router = useRouter();
const route = useRoute();

// 练习配置
const selectedSubject = ref('');
const selectedKnowledgePoint = ref('');
const exerciseCount = ref(10);
const difficulty = ref('中等');
const knowledgePoints = ref([]);
const knowledgePointsLoading = ref(false);

// 练习状态
const practicing = ref(false);
const currentQuestionIndex = ref(0);
const exercises = ref([]);
const userAnswers = ref([]);
const validatedAnswers = ref([]); // 存储已验证的答案
const startTime = ref(0);
const elapsedTime = ref(0);
const timer = ref(null);

// 答案验证状态
const answerValidated = ref(false);
const isCorrect = ref(false);
const validatedQuestionIndex = ref(-1);

// 练习结果
const showResult = ref(false);
const practiceResult = ref({
  correctRate: 0,
  totalTime: 0,
  score: 0,
  analysis: '',
  questions: []
});

// 学科列表
const subjects = ref([
  { id: 1, name: '语文', value: 'chinese' },
  { id: 2, name: '数学', value: 'math' },
  { id: 3, name: '英语', value: 'english' },
  { id: 4, name: '物理', value: 'physics' },
  { id: 5, name: '化学', value: 'chemistry' },
  { id: 6, name: '生物', value: 'biology' },
]);

// 当前习题
const currentExercise = computed(() => {
  if (exercises.value.length === 0 || currentQuestionIndex.value >= exercises.value.length) {
    return {};
  }
  return exercises.value[currentQuestionIndex.value];
});

// 是否可以开始练习
const canStartPractice = computed(() => {
  return selectedSubject.value !== '';
});

// 加载知识点列表
const loadKnowledgePoints = async () => {
  if (!selectedSubject.value) {
    knowledgePoints.value = [];
    return;
  }
  
  knowledgePointsLoading.value = true;
  
  try {
    // 使用英文subject值调用API
    const response = await axios.get(`/api/knowledge/subject/${selectedSubject.value}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data) {
      knowledgePoints.value = response.data.map((point, index) => ({
        id: point.id || index + 1,
        name: point.name
      }));
    }
  } catch (error) {
    console.error('获取知识点列表失败:', error);
    ElMessage.error('获取知识点列表失败，请稍后重试');
  } finally {
    knowledgePointsLoading.value = false;
  }
};

// 开始练习
const startPractice = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '准备题目中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    const response = await axios.get('/api/student/recommended-exercises', {
      params: {
        subject: selectedSubject.value, // 已经是英文值
        knowledgePoint: selectedKnowledgePoint.value || '',
        count: exerciseCount.value,
        difficulty: difficulty.value
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data && response.data.length > 0) {
      exercises.value = response.data.map(exercise => {
        // 处理选择题选项
        let options = [];
        if (exercise.type === '选择题' && exercise.options) {
          try {
            // 如果options是字符串，尝试解析为JSON
            if (typeof exercise.options === 'string') {
              options = JSON.parse(exercise.options);
            } else if (Array.isArray(exercise.options)) {
              options = exercise.options;
            } else if (typeof exercise.options === 'object') {
              // 如果是对象形式 {A: "选项1", B: "选项2"}
              options = Object.entries(exercise.options).map(([key, value]) => ({
                key,
                value
              }));
            }
          } catch (e) {
            console.error('解析选项失败:', e);
          }
        }
        
        return {
          id: exercise.id,
          type: exercise.type || '选择题',
          content: exercise.content,
          options: options,
          answer: exercise.answer,
          explanation: exercise.explanation || ''
        };
      });
      
      // 初始化用户答案数组
      userAnswers.value = new Array(exercises.value.length).fill('');
      
      // 开始练习
      practicing.value = true;
      currentQuestionIndex.value = 0;
      startTime.value = Date.now();
      
      // 启动计时器
      timer.value = setInterval(() => {
        elapsedTime.value = Math.floor((Date.now() - startTime.value) / 1000);
      }, 1000);
    } else {
      ElMessage.warning('未找到符合条件的练习题，请尝试其他条件');
    }
  } catch (error) {
    console.error('获取练习题失败:', error);
    ElMessage.error('获取练习题失败，请稍后重试');
  } finally {
    loading.close();
  }
};

// 选择选项（选择题）
const selectOption = (key) => {
  userAnswers.value[currentQuestionIndex.value] = key;
};

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
  }
};

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < exercises.value.length - 1) {
    currentQuestionIndex.value++;
    answerValidated.value = validatedAnswers.value[currentQuestionIndex.value] !== undefined;
    if (answerValidated.value) {
      isCorrect.value = validatedAnswers.value[currentQuestionIndex.value].isCorrect;
      validatedQuestionIndex.value = currentQuestionIndex.value;
    } else {
      answerValidated.value = false;
    }
  }
};

// 确认答案并继续
const confirmAnswer = () => {
  // 记录当前题目已确认
  if (!validatedAnswers.value[currentQuestionIndex.value]) {
    validatedAnswers.value[currentQuestionIndex.value] = {
      isCorrect: isCorrect.value,
      userAnswer: userAnswers.value[currentQuestionIndex.value],
      correctAnswer: currentExercise.value.answer
    };
  }
  
  // 如果是最后一题，则提交整个练习
  if (currentQuestionIndex.value === exercises.value.length - 1) {
    submitPractice();
  } else {
    // 否则前往下一题
    answerValidated.value = false;
    nextQuestion();
  }
};

// 跳转到指定题目
const goToQuestion = (index) => {
  if (index >= 0 && index < exercises.value.length) {
    currentQuestionIndex.value = index;
  }
};

// 检查答案
const checkAnswer = () => {
  const currentAnswer = userAnswers.value[currentQuestionIndex.value];
  const correctAnswer = currentExercise.value.answer;
  
  // 如果没有填写答案，提示用户
  if (!currentAnswer || currentAnswer.trim() === '') {
    ElMessage.warning('请先输入答案');
    return;
  }
  
  // 使用工具函数检查答案匹配度
  isCorrect.value = checkAnswerMatch(
    currentAnswer, 
    correctAnswer, 
    currentExercise.value.type
  );
  
  // 标记当前题目已验证
  answerValidated.value = true;
  validatedQuestionIndex.value = currentQuestionIndex.value;
  
  // 保存验证结果
  if (!validatedAnswers.value[currentQuestionIndex.value]) {
    validatedAnswers.value[currentQuestionIndex.value] = {
      isCorrect: isCorrect.value,
      userAnswer: currentAnswer,
      correctAnswer: correctAnswer
    };
  }
  
  // 保存到数据库
  saveLearningProgress(isCorrect.value);
}

// 保存学习进度和错题
const saveLearningProgress = async (isCorrect) => {
  try {
    const exercise = exercises.value[currentQuestionIndex.value];
    
    // 如果答案错误，保存到错题集
    if (!isCorrect) {
      await axios.post('/api/student/mistake-collection/add', {
        exerciseId: exercise.id,
        subject: selectedSubject.value,
        content: exercise.content,
        correctAnswer: exercise.answer,
        knowledgePoint: selectedKnowledgePoint.value || '综合'
      }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
    }
    
    // 更新学习进度
    await axios.post('/api/student/update-learning-progress', {
      subject: selectedSubject.value,
      knowledgePoint: selectedKnowledgePoint.value || '综合',
      isCorrect: isCorrect,
      exerciseType: exercise.type,
      exerciseId: exercise.id
    }, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
  } catch (error) {
    console.error('保存学习进度失败:', error);
  }
}

// 提交练习
const submitPractice = async () => {
  // 检查是否所有题目都已回答
  const unansweredQuestions = [];
  userAnswers.value.forEach((answer, index) => {
    if (!answer || answer.trim() === '') {
      unansweredQuestions.push(index + 1);
    }
  });
  
  if (unansweredQuestions.length > 0) {
    ElMessage.warning(`题目 ${unansweredQuestions.join(', ')} 尚未回答，确定要提交吗？`);
    return;
  }
  
  const loading = ElLoading.service({
    lock: true,
    text: '提交中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    // 计算正确题目数量
    const correctCount = exercises.value.filter((exercise, index) => {
      return userAnswers.value[index] === exercise.answer;
    }).length;
    
    // 准备提交数据
    const submission = {
      subject: selectedSubject.value, // 已经是英文值
      knowledgePoint: selectedKnowledgePoint.value || '',
      difficulty: difficulty.value,
      totalCount: exercises.value.length,
      correctCount: correctCount,
      completionTime: elapsedTime.value,
      answers: exercises.value.map((exercise, index) => ({
        exerciseId: exercise.id,
        userAnswer: userAnswers.value[index] || '',
        isCorrect: userAnswers.value[index] === exercise.answer
      }))
    };
    
    // 提交到后端
    const response = await axios.post('/api/student/submit-practice', submission, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    // 处理返回结果
    if (response.data) {
      // 停止计时器
      clearInterval(timer.value);
      
      // 保存错题到错题本
      const wrongAnswers = exercises.value.filter((exercise, index) => 
        userAnswers.value[index] !== exercise.answer
      );
      
      if (wrongAnswers.length > 0) {
        // 将错题添加到错题本
        await Promise.all(wrongAnswers.map(async (exercise) => {
          try {
            await axios.post('/api/student/mistake-collection/add', {
              exerciseId: exercise.id,
              subject: selectedSubject.value,
              content: exercise.content,
              correctAnswer: exercise.answer,
              knowledgePoint: selectedKnowledgePoint.value || '综合'
            }, {
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              }
            });
          } catch (err) {
            console.error('保存错题失败:', err);
          }
        }));
      }
      
      // 准备练习结果数据
      practiceResult.value = {
        correctRate: Math.round((correctCount / exercises.value.length) * 100),
        totalTime: elapsedTime.value,
        score: Math.round((correctCount / exercises.value.length) * 100),
        analysis: response.data.analysis || '练习完成！',
        questions: exercises.value.map((exercise, index) => ({
          content: exercise.content,
          userAnswer: userAnswers.value[index] || '未作答',
          correctAnswer: exercise.answer,
          isCorrect: userAnswers.value[index] === exercise.answer,
          explanation: exercise.explanation
        }))
      };
      
      // 显示结果对话框
      showResult.value = true;
    }
  } catch (error) {
    console.error('提交练习失败:', error);
    ElMessage.error('提交练习失败，请稍后重试');
  } finally {
    loading.close();
  }
};

// 重置练习
const resetPractice = () => {
  practicing.value = false;
  exercises.value = [];
  userAnswers.value = [];
  currentQuestionIndex.value = 0;
  elapsedTime.value = 0;
  showResult.value = false;
};

// 前往错题本
const goToErrorBook = () => {
  router.push('/student/errors');
};

// 格式化时间
const formatTime = (ms) => {
  const seconds = Math.floor(ms / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  
  return `${hours.toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
};

const generatedExercises = ref([]);
const loading = ref(false);

// 加载历史记录
const loadHistory = async () => {
  try {
    const response = await axios.get('/api/student/history/exercise', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data && Array.isArray(response.data)) {
      // 显示最近的一条历史记录
      const latestRecord = response.data[0];
      if (latestRecord) {
        selectedSubject.value = latestRecord.subject;
        requirement.value = latestRecord.requirement;
        generatedExercises.value = latestRecord.exercises;
      }
    }
  } catch (error) {
    console.error('加载历史记录失败:', error);
  }
};

// 生成习题
const generateExercises = async () => {
  if (!selectedSubject.value || !requirement.value.trim()) {
    ElMessage.warning('请选择学科并输入生成要求');
    return;
  }
  
  loading.value = true;
  
  try {
    const response = await axios.post('/api/student/generate-exercises', {
      subject: selectedSubject.value,
      requirement: requirement.value
    }, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data && response.data.exercises) {
      generatedExercises.value = response.data.exercises;
      
      // 保存到历史记录
      try {
        await axios.post('/api/student/history/exercise', {
          subject: selectedSubject.value,
          requirement: requirement.value,
          exercises: response.data.exercises,
          time: new Date()
        }, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
      } catch (error) {
        console.error('保存历史记录失败:', error);
      }
    } else {
      throw new Error('未收到有效的习题数据');
    }
  } catch (error) {
    console.error('生成习题失败:', error);
    ElMessage.error('生成习题失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 检查URL参数
  const relatedTo = route.query.relatedTo;
  const subjectId = route.query.subjectId;
  const subject = route.query.subject;
  
  if (subject) {
    selectedSubject.value = subject;
    loadKnowledgePoints();
  } else if (subjectId) {
    const subjectObj = subjects.value.find(s => s.id.toString() === subjectId.toString());
    if (subjectObj) {
      selectedSubject.value = subjectObj.name;
      loadKnowledgePoints();
    }
  }

  // 加载历史记录
  loadHistory();
});

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style scoped>
.practice {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-form {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.loading-text {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.form-actions {
  margin-top: 20px;
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
}

/* 练习区域样式 */
.practice-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.practice-progress {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.question-card {
  flex: 1;
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.question-type {
  font-weight: bold;
  color: #409EFF;
}

.question-info {
  color: #909399;
}

.question-content {
  margin-bottom: 20px;
  font-size: 16px;
  line-height: 1.6;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.option-item {
  display: flex;
  padding: 10px 15px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  background-color: #F5F7FA;
}

.option-selected {
  background-color: #ecf5ff;
  border-color: #409EFF;
}

.option-key {
  font-weight: bold;
  margin-right: 10px;
  min-width: 20px;
}

.question-fill, .question-answer {
  margin-bottom: 20px;
}

.question-actions {
  display: flex;
  justify-content: space-between;
}

.question-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 20px;
}

.nav-item {
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-current {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

.nav-answered {
  background-color: #F0F9EB;
  border-color: #67C23A;
}

/* 结果样式 */
.result-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
}

.result-item {
  text-align: center;
}

.result-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.result-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.result-analysis {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 6px;
}

.result-analysis h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #67C23A;
}

.result-questions h3 {
  margin-bottom: 15px;
}

.result-question {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
}

.question-status {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.status-correct {
  background-color: #F0F9EB;
  color: #67C23A;
}

.status-wrong {
  background-color: #FEF0F0;
  color: #F56C6C;
}

.answer-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin: 15px 0;
}

.answer-label, .explanation-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.your-answer {
  padding: 10px;
  background-color: #FEF0F0;
  border-radius: 4px;
}

.correct-answer {
  padding: 10px;
  background-color: #F0F9EB;
  border-radius: 4px;
}

.answer-explanation {
  padding: 10px;
  background-color: #ECF5FF;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .config-form {
    grid-template-columns: 1fr;
  }
  
  .answer-section {
    grid-template-columns: 1fr;
  }
}

.fill-answer-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.fill-label {
  font-weight: 500;
  min-width: 80px;
}

.check-btn {
  margin-left: 10px;
}

.validation-result {
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
  font-weight: bold;
}

.correct {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #67c23a;
}

.incorrect {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.correct-answer-display {
  margin-top: 8px;
  font-weight: normal;
}

.answer-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.blank-line {
  display: inline-block;
  width: 120px;
  height: 1.5em;
  border-bottom: 1px solid #333;
  margin: 0 5px;
  position: relative;
}

.nav-item.nav-correct {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.nav-item.nav-incorrect {
  background-color: #f56c6c;
  color: white;
  border-color: #f56c6c;
}

.answer-area {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9fafc;
}

.options-container {
  margin-bottom: 20px;
}

.options-label {
  font-weight: 500;
  margin-bottom: 10px;
  color: #606266;
}

.options-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.option-btn {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  font-weight: 500;
  transition: all 0.3s;
}

.option-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.option-btn.option-selected {
  border-color: #409eff;
  color: white;
  background-color: #409eff;
}

.essay-answer-container {
  margin-bottom: 20px;
}

.essay-label {
  font-weight: 500;
  margin-bottom: 10px;
  color: #606266;
}

.submit-btn {
  padding: 12px 24px;
  font-size: 16px;
}

.confirm-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.confirm-btn {
  padding: 12px 24px;
  font-size: 16px;
}
</style> 